package com.weiyi.mashangzhu.Landlord.Fragment;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;

import com.app.hubert.library.HighLight;
import com.app.hubert.library.NewbieGuide;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.okhttp.Request;
import com.weiyi.mashangzhu.API.API;
import com.weiyi.mashangzhu.Landlord.Activity.MainActivity_L;
import com.weiyi.mashangzhu.Landlord.Activity.PublishHouseActivity;
import com.weiyi.mashangzhu.Landlord.Adapter.HouseAdapter;
import com.weiyi.mashangzhu.Landlord.Bean.HouseBean_L;
import com.weiyi.mashangzhu.R;
import com.weiyi.mashangzhu.Utils.SPUtils;
import com.weiyi.mashangzhu.Utils.T;
import com.weiyi.mashangzhu.Utils.UiUtil;
import com.weiyi.mashangzhu.Weight.calendartest.entity.DayTimeEntity;
import com.weiyi.mashangzhu.Weight.calendartest.entity.MonthTimeEntity;
import com.weiyi.mashangzhu.Weight.calendartest.utils.SharePreferences;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class Fragment_House_L extends Fragment {
    private HouseAdapter adapter, adapter2;
    private ArrayList<MonthTimeEntity> datas;
    public static DayTimeEntity startDay;
    public static DayTimeEntity stopDay;
    SharePreferences isPreferences;
    private LayoutInflater mInflater;
    private View view1;
    private View view2;
    PullToRefreshListView pullToRefreshListView_up, pullToRefreshListView_down;
    private List<String> mTitleList = new ArrayList<>();//页卡标题集合
    private List<View> mViewList = new ArrayList<>();//页卡视图集合
    private int page = 1;
    private int page2 = 1;
    List<HouseBean_L.DataBean.OnsalehouselistBean> OnsalehouselistBeanlist = new ArrayList<>();
    List<HouseBean_L.DataBean.PutonsalehouselistBean> PutonsalehouselistBeanlist = new ArrayList<>();
    View view;
    TabLayout mTabLayout;
    ViewPager mViewPager;
    ImageView add;
    private MainActivity_L mainActivity;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainActivity = (MainActivity_L) getActivity();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        isPreferences = new SharePreferences(mainActivity);
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_house_l, container, false);
            mTabLayout = (TabLayout) view.findViewById(R.id.tabs);
            mViewPager = (ViewPager) view.findViewById(R.id.vp_view);
            add= (ImageView) view.findViewById(R.id.add);
            NewbieGuide.with(getActivity())//传入activity
                    .setLabel("guide2")//设置引导层标示，用于区分不同引导层，必传！否则报错
                    .addHighLight(add, HighLight.Type.RECTANGLE)//添加需要高亮的view
                    .setEveryWhereCancelable(false)//设置点击任何区域消失，默认为true
                    .setLayoutRes(R.layout.view_guide2,R.id.iv)//自定义的提示layout，不要添加背景色，引导层背景色通过setBackgroundColor()设置
                    .show();//显示引导层
            add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UiUtil.startActivity(mainActivity, PublishHouseActivity.class);
                }
            });
            mInflater = LayoutInflater.from(mainActivity);
            view1 = mInflater.inflate(R.layout.fragment_coupon_intime, null);
            view2 = mInflater.inflate(R.layout.fragment_coupon_outtime, null);
            pullToRefreshListView_up = (PullToRefreshListView) view1.findViewById(R.id.refresh_list);
            pullToRefreshListView_down = (PullToRefreshListView) view2.findViewById(R.id.refresh_list);
            //添加页卡视图
            mViewList.add(view1);
            mViewList.add(view2);

            //添加页卡标题
            mTitleList.add("上线中");
            mTitleList.add("已下线");


            mTabLayout.setTabMode(TabLayout.MODE_FIXED);//设置tab模式，当前为系统默认模式
            mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(0)));//添加tab选项卡
            mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(1)));


            MyPagerAdapter mAdapter = new MyPagerAdapter(mViewList);
            mViewPager.setAdapter(mAdapter);//给ViewPager设置适配器
            mTabLayout.setupWithViewPager(mViewPager);//将TabLayout和ViewPager关联起来。
            mTabLayout.setTabsFromPagerAdapter(mAdapter);//给Tabs设置适配器
            mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    initData(1);
                }

                @Override
                public void onTabUnselected(TabLayout.Tab tab) {

                }

                @Override
                public void onTabReselected(TabLayout.Tab tab) {

                }
            });
            initData(1);


            pullToRefreshListView_up
                    .setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
                        @Override
                        public void onPullDownToRefresh(
                                PullToRefreshBase<ListView> refreshView) {
                            Log.e("TAG", "onPullDownToRefresh");
                            //这里写下拉刷新的任务
                            new DownGetDataTask().execute();
                        }

                        @Override
                        public void onPullUpToRefresh(
                                PullToRefreshBase<ListView> refreshView) {
                            Log.e("TAG", "onPullUpToRefresh");
                            new UpGetDataTask().execute();
                        }
                    });
            pullToRefreshListView_down
                    .setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
                        @Override
                        public void onPullDownToRefresh(
                                PullToRefreshBase<ListView> refreshView) {
                            Log.e("TAG", "onPullDownToRefresh");
                            //这里写下拉刷新的任务
                            new DownGetDataTask2().execute();
                        }

                        @Override
                        public void onPullUpToRefresh(
                                PullToRefreshBase<ListView> refreshView) {
                            Log.e("TAG", "onPullUpToRefresh");
                            new UpGetDataTask2().execute();
                        }
                    });

        } else {


//缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。


            ViewGroup parent = (ViewGroup) view.getParent();


            if (parent != null) {


                parent.removeView(view);


            }


        }


        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        initData(1);
    }

    private void initData(final int i) {
        OkHttpUtils.get().addParams("token", SPUtils.get(mainActivity, "token", "") + "").addParams("pagenum", i + "")
                .url(API.BaseApi_L + API.GetHouse_L_Api)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        T.showShort(getActivity(), "网络连接失败，请检查一下网络设置");
                    }

                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.getInt("status") == 0) {
                                HouseBean_L housebean_l = new Gson().fromJson(response, HouseBean_L.class);
                                if (i == 1) {
                                    OnsalehouselistBeanlist.clear();
                                    PutonsalehouselistBeanlist.clear();
                                    OnsalehouselistBeanlist = housebean_l.getData().getOnsalehouselist();
                                    PutonsalehouselistBeanlist = housebean_l.getData().getPutonsalehouselist();
                                    adapter = new HouseAdapter(OnsalehouselistBeanlist, null,mainActivity, "o");
                                    adapter2 = new HouseAdapter(null, PutonsalehouselistBeanlist, mainActivity, "p");
                                    pullToRefreshListView_up.setAdapter(adapter);
                                    pullToRefreshListView_down.setAdapter(adapter2);
                                } else {
                                    OnsalehouselistBeanlist.addAll(housebean_l.getData().getOnsalehouselist());
                                    PutonsalehouselistBeanlist.addAll(housebean_l.getData().getPutonsalehouselist());
                                    adapter.notifyDataSetChanged();
                                    adapter2.notifyDataSetChanged();
                                }

                            } else {
                                SPUtils.put(mainActivity, "isLogin", "0");
                                T.showShort(mainActivity, jsonObject.getString("msg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                });
    }


    private class DownGetDataTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            try {
                Thread.sleep(1000);


            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            page = 1;
            initData(page);
            pullToRefreshListView_up.onRefreshComplete();
        }
    }

    private class UpGetDataTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            try {
                Thread.sleep(1000);

            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            page += 1;
            initData(page);
            pullToRefreshListView_up.onRefreshComplete();
        }
    }

    private class DownGetDataTask2 extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            try {
                Thread.sleep(1000);


            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            page = 1;
            initData(page);
            pullToRefreshListView_down.onRefreshComplete();
        }
    }

    private class UpGetDataTask2 extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            try {
                Thread.sleep(1000);

            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            page += 1;
            initData(page);
            pullToRefreshListView_down.onRefreshComplete();
        }
    }

    //ViewPager适配器
    class MyPagerAdapter extends PagerAdapter {
        private List<View> mViewList;

        public MyPagerAdapter(List<View> mViewList) {
            this.mViewList = mViewList;
        }

        @Override
        public int getCount() {
            return mViewList.size();//页卡数
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;//官方推荐写法
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mViewList.get(position));//添加页卡
            return mViewList.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViewList.get(position));//删除页卡
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitleList.get(position);//页卡标题
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

}
